package com.christina.engine.decision.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.christina.engine.decision.DecisionEngine;
import com.christina.engine.decision.model.DecisionRequest;
import com.christina.engine.decision.model.DecisionResult;
import com.christina.engine.intent.model.Intent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 基于AI的决策引擎实现
 * 
 * @author Christina
 */
@Slf4j
@Component
public class AiDecisionEngine implements DecisionEngine {

    private final ChatClient chatClient;
    private final ObjectMapper objectMapper;

    public AiDecisionEngine(ChatClient chatClient, ObjectMapper objectMapper) {
        this.chatClient = chatClient;
        this.objectMapper = objectMapper;
    }

    @Override
    public DecisionResult makeDecision(DecisionRequest request) {
        log.info("开始执行决策: 意图={}, 用户={}", request.getIntent().getType(), request.getUserId());
        
        try {
            // 基于意图类型进行决策路由
            DecisionResult result = routeByIntent(request);
            
            // 使用AI增强决策
            result = enhanceDecisionWithAi(request, result);
            
            log.info("决策完成: {} -> {}", result.getAction(), result.getTargetService());
            return result;
            
        } catch (Exception e) {
            log.error("决策执行失败", e);
            return buildFallbackDecision(request);
        }
    }

    @Override
    public double evaluateDecisionQuality(DecisionRequest request, DecisionResult result) {
        // 基于多个维度评估决策质量
        double intentMatchScore = calculateIntentMatchScore(request.getIntent(), result);
        double confidenceScore = result.getConfidence();
        double contextRelevanceScore = calculateContextRelevanceScore(request, result);
        
        return (intentMatchScore * 0.4 + confidenceScore * 0.3 + contextRelevanceScore * 0.3);
    }

    @Override
    public String explainDecision(DecisionRequest request, DecisionResult result) {
        StringBuilder explanation = new StringBuilder();
        
        explanation.append("决策分析：\n");
        explanation.append("1. 识别意图：").append(request.getIntent().getType().getDescription()).append("\n");
        explanation.append("2. 决策动作：").append(result.getAction().getDescription()).append("\n");
        explanation.append("3. 目标服务：").append(result.getTargetService()).append("\n");
        explanation.append("4. 置信度：").append(String.format("%.2f", result.getConfidence())).append("\n");
        explanation.append("5. 决策理由：").append(result.getReasoning()).append("\n");
        
        return explanation.toString();
    }

    /**
     * 基于意图进行决策路由
     */
    private DecisionResult routeByIntent(DecisionRequest request) {
        Intent.IntentType intentType = request.getIntent().getType();
        
        DecisionResult.DecisionResultBuilder builder = DecisionResult.builder()
            .decisionId(generateDecisionId())
            .decisionTime(LocalDateTime.now())
            .status(DecisionResult.DecisionStatus.PENDING);

        return switch (intentType) {
            case TRAVEL_PLANNING, TRAVEL_BOOKING, TRAVEL_INQUIRY, TRAVEL_MODIFICATION, TRAVEL_CANCELLATION -> builder
                    .action(DecisionResult.DecisionAction.EXECUTE_SERVICE)
                    .targetService("travel")
                    .confidence(0.9)
                    .reasoning("出行相关意图，路由到出行服务")
                    .executionParameters(request.getParameters())
                    .build();
            case GENERAL_CHAT, QUESTION_ANSWER, RECOMMENDATION -> builder
                    .action(DecisionResult.DecisionAction.EXECUTE_SERVICE)
                    .targetService("chat")
                    .confidence(0.8)
                    .reasoning("聊天相关意图，路由到聊天服务")
                    .executionParameters(request.getParameters())
                    .build();
            case USER_REGISTRATION, USER_LOGIN, USER_PROFILE -> builder
                    .action(DecisionResult.DecisionAction.EXECUTE_SERVICE)
                    .targetService("user")
                    .confidence(0.95)
                    .reasoning("用户相关意图，路由到用户服务")
                    .executionParameters(request.getParameters())
                    .build();
            case HELP_REQUEST -> builder
                    .action(DecisionResult.DecisionAction.PROVIDE_SUGGESTIONS)
                    .targetService("help")
                    .confidence(0.7)
                    .reasoning("帮助请求，提供使用建议")
                    .executionParameters(new JSONObject())
                    .build();
            case COMPLAINT -> builder
                    .action(DecisionResult.DecisionAction.DELEGATE_TO_HUMAN)
                    .targetService("human")
                    .confidence(0.8)
                    .reasoning("投诉处理，转人工客服")
                    .executionParameters(new JSONObject())
                    .build();
            default -> builder
                    .action(DecisionResult.DecisionAction.REQUEST_MORE_INFO)
                    .targetService("clarification")
                    .confidence(0.3)
                    .reasoning("意图不明确，需要更多信息")
                    .executionParameters(new JSONObject())
                    .build();
        };
    }

    /**
     * 使用AI增强决策
     */
    private DecisionResult enhanceDecisionWithAi(DecisionRequest request, DecisionResult baseResult) {
        try {
            String prompt = buildDecisionEnhancementPrompt(request, baseResult);
            String aiResponse = chatClient.prompt(prompt).call().content();
            
            // 解析AI建议并调整决策
            return adjustDecisionWithAiAdvice(baseResult, aiResponse);
            
        } catch (Exception e) {
            log.error("AI决策增强失败", e);
            return baseResult;
        }
    }

    /**
     * 构建决策增强提示词
     */
    private String buildDecisionEnhancementPrompt(DecisionRequest request, DecisionResult baseResult) {
        // 安全获取意图描述，避免空指针
        String intentDescription = "未知意图";
        if (request != null && request.getIntent() != null && request.getIntent().getType() != null) {
            intentDescription = Objects.toString(request.getIntent().getType().getDescription(), "未知意图");
        }
        
        // 安全获取动作描述，避免空指针
        String actionDescription = "未知动作";
        if (baseResult != null && baseResult.getAction() != null) {
            actionDescription = Objects.toString(baseResult.getAction().getDescription(), "未知动作");
        }
        
        // 安全获取目标服务
        String targetService = "";
        if (baseResult != null) {
            targetService = Objects.toString(baseResult.getTargetService(), "");
        }
        
        // 安全获取置信度，避免NaN或无穷大
        double confidence = 0.0;
        if (baseResult != null) {
            confidence = baseResult.getConfidence();
            // 确保置信度在合理范围内
            if (Double.isNaN(confidence) || Double.isInfinite(confidence)) {
                confidence = 0.0;
            }
            confidence = Math.max(0.0, Math.min(1.0, confidence)); // 限制在0-1范围内
        }
        
        // 安全获取决策理由
        String reasoning = "";
        if (baseResult != null) {
            reasoning = Objects.toString(baseResult.getReasoning(), "");
        }
        
        return String.format("""
            请分析以下决策是否合理，并提供优化建议：
            
            用户意图：%s
            当前决策：%s -> %s
            置信度：%.2f
            决策理由：%s
            
            请考虑：
            1. 决策是否符合用户意图
            2. 是否有更好的处理方式
            3. 置信度是否合理
            4. 是否需要额外的处理步骤
            
            请以JSON格式返回优化建议：
            {
                "isOptimal": true/false,
                "suggestedAction": "建议的动作",
                "suggestedService": "建议的服务",
                "adjustedConfidence": 0.95,
                "reasoning": "优化理由"
            }
            """,
            intentDescription,
            actionDescription,
            targetService,
            confidence,
            reasoning
        );
    }

    /**
     * 根据AI建议调整决策
     */
    private DecisionResult adjustDecisionWithAiAdvice(DecisionResult baseResult, String aiAdvice) {
        try {
            // 提取JSON部分
            String jsonPart = extractJsonFromResponse(aiAdvice);
            JSONObject advice = JSON.parseObject(jsonPart);
            
            boolean isOptimal = (Boolean) advice.get("isOptimal");
            if (isOptimal) {
                return baseResult; // 当前决策已经是最优的
            }
            
            // 应用AI建议
            String suggestedAction = (String) advice.get("suggestedAction");
            String suggestedService = (String) advice.get("suggestedService");
            double adjustedConfidence = ((Number) advice.get("adjustedConfidence")).doubleValue();
            String reasoning = (String) advice.get("reasoning");
            
            // 使用builder重新构建DecisionResult
            return DecisionResult.builder()
                .decisionId(baseResult.getDecisionId())
                .action(parseDecisionAction(suggestedAction))
                .targetService(suggestedService)
                .confidence(adjustedConfidence)
                .reasoning(reasoning)
                .decisionTime(baseResult.getDecisionTime())
                .status(baseResult.getStatus())
                .executionParameters(baseResult.getExecutionParameters())
                .alternatives(baseResult.getAlternatives())
                .build();
                
        } catch (Exception e) {
            log.error("解析AI决策建议失败: {}", aiAdvice, e);
            return baseResult;
        }
    }

    /**
     * 解析决策动作
     */
    private DecisionResult.DecisionAction parseDecisionAction(String actionStr) {
        try {
            return DecisionResult.DecisionAction.valueOf(actionStr.toUpperCase().replace(" ", "_"));
        } catch (Exception e) {
            return DecisionResult.DecisionAction.EXECUTE_SERVICE;
        }
    }

    /**
     * 构建兜底决策
     */
    private DecisionResult buildFallbackDecision(DecisionRequest request) {
        return DecisionResult.builder()
            .decisionId(generateDecisionId())
            .action(DecisionResult.DecisionAction.PROVIDE_SUGGESTIONS)
            .targetService("fallback")
            .confidence(0.1)
            .reasoning("决策引擎异常，使用兜底策略")
            .decisionTime(LocalDateTime.now())
            .status(DecisionResult.DecisionStatus.COMPLETED)
            .executionParameters(new JSONObject())
            .alternatives(new ArrayList<>())
            .build();
    }

    /**
     * 计算意图匹配分数
     */
    private double calculateIntentMatchScore(Intent intent, DecisionResult result) {
        // 简化的匹配分数计算逻辑
        return 0.8;
    }

    /**
     * 计算上下文相关性分数
     */
    private double calculateContextRelevanceScore(DecisionRequest request, DecisionResult result) {
        // 简化的相关性分数计算逻辑
        return 0.7;
    }

    /**
     * 从AI响应中提取JSON部分
     */
    private String extractJsonFromResponse(String response) {
        // 简化的JSON提取逻辑
        int start = response.indexOf("{");
        int end = response.lastIndexOf("}") + 1;
        if (start >= 0 && end > start) {
            return response.substring(start, end);
        }
        return "{}";
    }

    /**
     * 生成决策ID
     */
    private String generateDecisionId() {
        return "decision_" + System.currentTimeMillis();
    }
}